package com.example.demo.service;

import com.example.demo.model.ProductionTracking;
import com.example.demo.repository.ProductionTrackingDao;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ProductionTrackingService {
    private final ProductionTrackingDao productionTrackingDao;

    public ProductionTrackingService(ProductionTrackingDao productionTrackingDao) {
        this.productionTrackingDao = productionTrackingDao;
    }

    public ProductionTrackingDao getProductionTrackingDao() {
        return productionTrackingDao;
    }

    public int addProductionTracking(ProductionTracking productionTracking) {
        if (productionTrackingDao.existsByPlanId(productionTracking.getPlan_id())) {
            throw new RuntimeException("计划ID " + productionTracking.getPlan_id() + " 已存在，请使用其他ID");
        }
        return productionTrackingDao.insertProductionTracking(productionTracking);
    }

    public int updateProductionTracking(ProductionTracking productionTracking) {
        return productionTrackingDao.updateProductionTracking(productionTracking);
    }

    public List<ProductionTracking> getAllProductionTracking() {
        return productionTrackingDao.getAllProductionTracking();
    }

    public ProductionTracking getProductionTrackingById(int id) {
        return productionTrackingDao.getProductionTracking(id);
    }

    public void deleteProductionTracking(int id) {
        productionTrackingDao.deleteProductionTracking(id);
    }

    public Page<ProductionTracking> searchProductionTracking(String productName, String department, Integer managerId, String auditStatus, String batchNumber, Pageable pageable) {
        int totalCount = productionTrackingDao.countSearchProductionTracking(productName, department, managerId, auditStatus, batchNumber);
        List<ProductionTracking> list = productionTrackingDao.searchProductionTracking(productName, department, managerId, auditStatus, batchNumber, pageable);
        return new PageImpl<>(list, pageable, totalCount);
    }

    /**
     * 计算审核通过的信息数与总信息数的比例
     * @return 审核通过的信息数与总信息数的比例
     */
    public double getApprovedRatio() {
        int approvedCount = productionTrackingDao.countApprovedProductionTracking();
        int totalCount = productionTrackingDao.countAllProductionTracking();
        System.out.println("approvedCount" + approvedCount);
        System.out.println("totalCount" + totalCount);
        return totalCount == 0 ? 0 : (double) approvedCount / totalCount;
    }
}